﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using TeamDev.SDK;

namespace TDB.Services
{
  /// <summary>
  /// This Class is used to remove Objects from the store that are not more referenced by indexes. 
  /// This process can take a lot of time and so is executed from an external process. 
  /// </summary>
  internal static class Cleaning
  {
    private static Timer tt = null;
    private static TimeSpan _cleanupperiod = new TimeSpan(0, 10, 0);

    public static void Start()
    {
      EventLogWriter.LogMessage("Starting Cleanup agent ...", System.Diagnostics.EventLogEntryType.Information);

      tt = new Timer(o =>
      {
        Thread ct = new Thread((ThreadStart)delegate { Clean(); });
        ct.Start();
      });
      tt.Change(_cleanupperiod, _cleanupperiod);

      EventLogWriter.LogMessage(string.Format("Next DB Cleanup at {0}  ...", DateTime.Now.Add(_cleanupperiod).ToLongTimeString()), System.Diagnostics.EventLogEntryType.Information);
    }

    public static void Stop()
    {
      if (tt != null)
      {
        tt.Change(-1, -1);
        tt.Dispose();
        tt = null;
      }
    }

    public static void Clean()
    {      
      //foreach (var sname in Server.GetStores())
      //{
      //  var store = Server.GetStore(sname);
      //  store.Purge();
      //}
      //EventLogWriter.LogMessage(string.Format("DB Cleanup Executed. Next DB Cleanup at {0}  ...", DateTime.Now.Add(_cleanupperiod).ToLongTimeString()), System.Diagnostics.EventLogEntryType.Information);
    }
  }
}
